import 'dart:async';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:chatbot/manager/dio_manager.dart';
import 'package:chatbot/manager/event_bus.dart';
import 'package:chatbot/manager/store_manager.dart';
import 'package:chatbot/model/event.dart';
import 'package:chatbot/model/role_list_model.dart';
import 'package:chatbot/model/role_model.dart';
import 'package:chatbot/page/chat_page.dart';
import 'package:chatbot/utils/utils.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:cupertino_listview/cupertino_listview.dart';
import 'package:flutter/cupertino.dart';
import 'dart:convert';
import 'package:chatbot/utils/colors.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:speech_to_text/speech_to_text.dart';
import 'package:speech_to_text/speech_to_text_provider.dart';

class RoleTabPage extends StatefulWidget {
  final bool isSelectRole;
  final SpeechToText speech;

  final SpeechToTextProvider speechProvider;

  const RoleTabPage(
      {super.key,
      this.isSelectRole = false,
      required this.speech,
      required this.speechProvider});

  @override
  _RoleTabPageState createState() => _RoleTabPageState();
}

class _RoleTabPageState extends State<RoleTabPage>
    with TickerProviderStateMixin {
  late TabController _tabController;
  List tabs = [];
  List<RoleSection> roleSectionList = [];
  final String allRoleTitle = "全部";
  late StreamSubscription subscription;

  @override
  void initState() {
    super.initState();


    subscription = Connectivity()
        .onConnectivityChanged
        .listen((ConnectivityResult result) {
      if (result == ConnectivityResult.mobile ||
          result == ConnectivityResult.wifi) {
        getRolesFromLocal();
        getRolesFromNet();
      }
    });
  }
  getRolesFromNet() async{
    int currentPage = 1;
    List<Role> roleList = [];
    bool isLastPage = false;
    int totals = 0;
    while(!isLastPage) {
      RoleListModel roleListModel = await DioManager.instance
          .getAllRoles(currentPage);
      if (roleListModel.data.list.isNotEmpty) {
        currentPage += 1;
        totals = roleListModel.data.total;
        roleList.addAll(roleListModel.data.list);
        isLastPage = roleListModel.data.isLastPage;
      }
    }

    parseList(roleList);
    if(totals == roleList.length){
      debugPrint("save to local");
      String jsonString = json.encode(roleList);
      StoreManager.putRoleJson(jsonString);
    }
  }
  getRolesFromLocal() {
    String? roleJsonString = StoreManager.getRoleJson();
    List mapList = json.decode(roleJsonString);
    List<Role>roleList = [];
    for(Map<String,dynamic> map in mapList){
      roleList.add(Role.fromMap(map));
    }

    parseList(roleList);
  }

  void parseList(List<dynamic> list) {
    if (list.isNotEmpty) {
      debugPrint("local list size=${list.length}");
      Role? previousRole;
      int index = -1;
      roleSectionList = [];
      tabs = [];
      tabs.add(allRoleTitle);
      for (Role role in list) {
        if (previousRole == null || role.category != previousRole.category) {
          index = index + 1;
          var sectionRole = RoleSection();
          sectionRole.data = [];
          sectionRole.title = role.category;
          tabs.add(role.category);
          roleSectionList.add(sectionRole);
          previousRole = role;
        }

        roleSectionList[index].data.add(role);
      }
      // if(tabs.isEmpty) {
        _tabController = TabController(length: tabs.length, vsync: this);
      // }
    }
    setState(() {});
  }

  isResponseSuccess(Map response) {
    return response.containsKey('code') && response['code'] == 200;
  }

  @override
  Widget build(BuildContext context) {
    return tabs.isEmpty
        ? Scaffold(
            backgroundColor: ChatColors.lightColor,
            body: Center(
              child: CupertinoActivityIndicator(
                  radius: 10.0, color: ChatColors.primaryColor),
            ),
          )
        : Scaffold(
            backgroundColor: ChatColors.darkColor,
            appBar: AppBar(
              backgroundColor: ChatColors.lightColor,
              leading: widget.isSelectRole
                  ? IconButton(
                      onPressed: () {
                        Navigator.pop(context);
                      },
                      icon: const Icon(
                        Icons.arrow_back_ios,
                        color: Colors.black,
                        size: 20,
                      ))
                  : null,
              actions: [
                widget.isSelectRole
                    ? InkWell(
                        onTap: () {
                          StoreManager.setHomeRolePrompt("");
                          StoreManager.setHomeRoleName("AI");
                          StoreManager.setHomeRoleTips(Utils.defaultTips);
                          EventManager.instance.eventBus
                              .fire(SwitchRoleEvent());
                          Navigator.pop(context);
                        },
                        child: Padding(
                          padding: const EdgeInsets.only(right: 8.0),
                          child: Text(
                            "默认",
                            style: TextStyle(
                                color: ChatColors.primaryColor,
                                fontSize: 13,
                                fontWeight: FontWeight.w700),
                          ),
                        ))
                    : Container()
              ],
              title: Text(
                widget.isSelectRole ? "切换角色" : "助手",
                style: const TextStyle(
                    color: Colors.black,
                    fontSize: 16,
                    fontWeight: FontWeight.w600),
              ),
              bottom: TabBar(
                isScrollable: true,
                unselectedLabelColor: Colors.black87,
                labelStyle: TextStyle(
                    color: ChatColors.primaryColor,
                    fontSize: 16,
                    fontWeight: FontWeight.w600),
                unselectedLabelStyle:
                    const TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
                dividerColor: ChatColors.darkColor,
                indicatorColor: ChatColors.primaryColor,
                controller: _tabController,
                tabs: tabs.map((e) => Tab(text: e)).toList(),
              ),
            ),
            body: TabBarView(
              //构建
              controller: _tabController,
              children: tabs.map((e) {
                if (e == allRoleTitle) {
                  return AllRolePage(
                    roleSectionList: roleSectionList,
                    title: e,
                    isSelectRole: widget.isSelectRole,
                    speech: widget.speech,
                    speechProvider: widget.speechProvider,
                  );
                } else {
                  return RolePage(
                    roleSectionList: roleSectionList,
                    title: e,
                    isSelectRole: widget.isSelectRole,
                    speech: widget.speech,
                    speechProvider: widget.speechProvider,
                  );
                }
              }).toList(),
            ),
          );
  }

  @override
  void dispose() {
    // 释放资源
    _tabController.dispose();
    super.dispose();
  }
}

class RolePage extends StatefulWidget {
  final List<RoleSection> roleSectionList;
  final String title;
  final bool isSelectRole;
  final SpeechToText speech;

  final SpeechToTextProvider speechProvider;

  const RolePage(
      {super.key,
      required this.roleSectionList,
      required this.title,
      required this.isSelectRole,
      required this.speech,
      required this.speechProvider});

  @override
  State<StatefulWidget> createState() {
    return RoleState(roleSectionList: roleSectionList, title: title);
  }
}

class RoleState extends State<RolePage> {
  final List<RoleSection> roleSectionList;
  final String title;
  List<Role> roleList = [];

  RoleState({required this.roleSectionList, required this.title});

  @override
  void initState() {
    super.initState();
    setState(() {
      for (RoleSection section in roleSectionList) {
        if (section.title == title) {
          roleList.addAll(section.data);
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ChatColors.darkColor,
      body: ListView.builder(
          itemCount: roleList.length,
          itemBuilder: (BuildContext context, int index) {
            Role role = roleList[index];
            return RoleItem(role, widget.isSelectRole,widget.speech,widget.speechProvider);
          }),
    );
  }
}

class AllRolePage extends StatefulWidget {
  final List<RoleSection> roleSectionList;
  final String title;
  final bool isSelectRole;
  final SpeechToText speech;

  final SpeechToTextProvider speechProvider;

  const AllRolePage(
      {super.key,
      required this.roleSectionList,
      required this.title,
      required this.isSelectRole,
      required this.speech,
      required this.speechProvider});

  @override
  State<StatefulWidget> createState() {
    return AllRoleState(roleSectionList: roleSectionList, title: title);
  }
}

class AllRoleState extends State<AllRolePage> {
  final List<RoleSection> roleSectionList;
  final String title;

  AllRoleState({required this.roleSectionList, required this.title});

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ChatColors.darkColor,
      body: CupertinoListView.builder(
        sectionCount: roleSectionList.length,
        itemInSectionCount: (section) => roleSectionList[section].data.length,
        sectionBuilder: (context, sectionPath, _) => Container(
          color: ChatColors.darkColor,
          width: MediaQuery.of(context).size.width,
          padding: const EdgeInsets.only(left: 12, top: 12, bottom: 6),
          child: Text(
            roleSectionList[sectionPath.section].title,
            style: const TextStyle(
                color: Colors.black, fontSize: 17, fontWeight: FontWeight.w800),
          ),
        ),
        childBuilder: (context, indexPath) => RoleItem(
            roleSectionList[indexPath.section].data[indexPath.child],
            widget.isSelectRole,widget.speech,widget.speechProvider),
        separatorBuilder: (context, indexPath) => Container(
          height: 3,
        ),
      ),
    );
  }
}

class RoleItem extends StatelessWidget {
  final Role role;
  final bool isSelectRole;
  final SpeechToText speech;

  final SpeechToTextProvider speechProvider;
  const RoleItem(this.role, this.isSelectRole,this.speech,this.speechProvider);

  @override
  Widget build(BuildContext context) {
    return InkWell(
      highlightColor: Colors.transparent, // 透明色
      splashColor: Colors.transparent, // 透明色
      onTap: () {
        if (isSelectRole) {
          StoreManager.setHomeRolePrompt(role.prompt);
          StoreManager.setHomeRoleName(role.title);
          StoreManager.setHomeRoleTips(role.subTitle);
          EventManager.instance.eventBus.fire(SwitchRoleEvent());
          Navigator.pop(context);
        } else {
          Navigator.push(context,
              CupertinoPageRoute(builder: (BuildContext context) {
            return ChatPage(
              rolePrompt: role.prompt,
              roleName: role.title,
              roleTips: role.subTitle,
              type: role.type,
              speech: speech,
              speechProvider: speechProvider,
            );
          }));
        }
      },
      child: Container(
        margin: const EdgeInsets.fromLTRB(16, 8, 16, 0),
        height: 64,
        width: MediaQuery.of(context).size.width - 32,
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: const BorderRadius.all(Radius.circular(8.0)),
        ),
        child: Stack(
          children: [
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Padding(
                  padding: const EdgeInsets.only(left: 12, top: 12, right: 16),
                  child: Container(
                      width: 28,
                      height: 28,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(
                        color: ChatColors.primaryColor,
                        borderRadius: const BorderRadius.all(Radius.circular(28.0)),
                      ),
                      child: CachedNetworkImage(
                        imageUrl: role.cover,
                        width: 28,
                        height: 28,
                        fit: BoxFit.cover,
                        // placeholder: (context, url) =>
                        //     const CircularProgressIndicator(color: Colors.grey),
                        errorWidget: (context, url, error) {
                          // debugPrint(error);
                          return const Icon(Icons.hourglass_empty);
                        },
                      )),
                ),
                Expanded(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Text(
                            role.title,
                            style: const TextStyle(
                                color: Colors.black,
                                fontSize: 15,
                                fontWeight: FontWeight.w800),
                          ),
                          // const Padding(
                          //   padding: EdgeInsets.only(left:6,right: 3),
                          //   child: Icon(
                          //     Icons.local_fire_department,
                          //     color: Colors.red,
                          //     size: 16,
                          //   ),
                          // ),
                          // Text(
                          //   role.users,
                          //   style:  TextStyle(
                          //     color: Colors.white.withOpacity(0.6),
                          //     fontSize: 12,
                          //   ),
                          // ),
                        ],
                      ),
                      Padding(
                        padding: const EdgeInsets.only(top: 6.0, right: 66),
                        child: Text(
                          role.subTitle,
                          overflow: TextOverflow.ellipsis,
                          maxLines: 1,
                          style: TextStyle(
                              color: Colors.black.withOpacity(0.8),
                              fontSize: 13,
                              fontWeight: FontWeight.w500),
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            Positioned(
              right: 0,
              child: Container(
                  margin: const EdgeInsets.fromLTRB(12, 24, 12, 0),
                  padding: const EdgeInsets.fromLTRB(12, 4, 12, 4),
                  decoration: BoxDecoration(
                    color: ChatColors.primaryColor,
                    borderRadius: const BorderRadius.all(Radius.circular(16.0)),
                  ),
                  child: Text(
                    isSelectRole ? "切换" : role.jumpTitle,
                    style: const TextStyle(
                        color: Colors.white,
                        fontSize: 13,
                        fontWeight: FontWeight.w600),
                  )),
            ),
          ],
        ),
      ),
    );
  }
}
